/**
 * @file consumer_example.cpp
 * @brief MessageFramework消费者示例
 *
 * 展示如何使用MessageConsumer接收和处理消息
 */

#include "MessageConsumer.h"
#include "MessageDispatcher.h"
#include "handlers/TradeSignalHandler.h"
#include "handlers/APIRequestHandler.h"
#include "RedisPool.h"
#include <spdlog/spdlog.h>
#include <iostream>
#include <csignal>
#include <atomic>

using namespace MessageFramework;

std::atomic<bool> g_running(true);

void signalHandler(int signal) {
    std::cout << "\n收到信号 " << signal << "，正在停止..." << std::endl;
    g_running = false;
}

int main() {
    spdlog::set_level(spdlog::level::debug);

    // 注册信号处理
    std::signal(SIGINT, signalHandler);
    std::signal(SIGTERM, signalHandler);

    // 1. 初始化Redis连接池
    RedisPool::Config redisConfig;
    redisConfig.host = "127.0.0.1";
    redisConfig.port = 6379;
    redisConfig.password = "redis_EX7Nms";
    redisConfig.poolSize = 5;

    RedisPool* redisPool = RedisPool::getInstance();
    redisPool->init(redisConfig);

    // 2. 创建消息分发器
    MessageDispatcher::Config dispatcherConfig;
    dispatcherConfig.secretKey = "your-secret-key-32bytes-long!!!";
    dispatcherConfig.verifySignature = true;
    dispatcherConfig.autoDecrypt = true;
    dispatcherConfig.encryptionKey = ""; // 如果有加密消息，需要设置密钥

    auto dispatcher = std::make_shared<MessageDispatcher>(dispatcherConfig);

    // 3. 创建并注册TradeSignalHandler
    auto tradeSignalHandler = std::make_shared<TradeSignalHandler>();
    tradeSignalHandler->setCallback([](const TradingSignalBody& signal,
                                       const MessageHeader& header) -> int {
        std::cout << "\n📈 收到交易信号：" << std::endl;
        std::cout << "   MessageID: " << header.messageId << std::endl;
        std::cout << "   Publisher: " << header.publisherId << std::endl;
        std::cout << "   合约: " << signal.instrumentId << std::endl;
        std::cout << "   方向: " << signal.direction << " " << signal.offsetFlag << std::endl;
        std::cout << "   价格: " << signal.price << std::endl;
        std::cout << "   数量: " << signal.volume << std::endl;
        std::cout << "   策略: " << signal.strategyId << std::endl;
        std::cout << "   备注: " << signal.comment << std::endl;

        // 这里应该调用TraderEngine执行交易
        // TraderEngine* engine = getTraderEngine();
        // engine->placeOrder(...);

        return 0;  // 成功
    });

    dispatcher->registerHandler("TradeSignal", tradeSignalHandler);

    // 4. 创建并注册APIRequestHandler
    auto producerForResponse = std::make_shared<MessageProducer>(redisPool, "TraderManager-1");

    auto apiRequestHandler = std::make_shared<APIRequestHandler>();
    apiRequestHandler->setProducer(producerForResponse);
    apiRequestHandler->setCallback([](const APIRequestBody& request,
                                      const MessageHeader& header) -> APIResponseBody {
        std::cout << "\n📡 收到API请求：" << std::endl;
        std::cout << "   MessageID: " << header.messageId << std::endl;
        std::cout << "   Publisher: " << header.publisherId << std::endl;
        std::cout << "   请求类型: " << request.requestType << std::endl;
        std::cout << "   用户ID: " << request.userId << std::endl;
        std::cout << "   参数: " << request.params << std::endl;

        // 模拟处理请求
        APIResponseBody response;
        response.code = 0;
        std::strcpy(response.message, "Success");

        // 根据请求类型返回不同数据
        if (std::strcmp(request.requestType, "QUERY_ACCOUNT") == 0) {
            std::strcpy(response.data,
                       "{\"balance\":100000.0,\"available\":80000.0,\"frozen\":20000.0}");
        } else if (std::strcmp(request.requestType, "QUERY_POSITION") == 0) {
            std::strcpy(response.data,
                       "[{\"instrument\":\"rb2501\",\"volume\":2,\"price\":4000.0}]");
        } else {
            std::strcpy(response.data, "{}");
        }

        std::cout << "   ✅ 响应数据: " << response.data << std::endl;

        return response;
    });

    dispatcher->registerHandler("APIRequest", apiRequestHandler);

    // 5. 创建消息消费者
    MessageConsumer::Config consumerConfig;
    consumerConfig.streamName = "trading_signals";
    consumerConfig.consumerGroup = "trader_group";
    consumerConfig.consumerId = "TraderManager-1";
    consumerConfig.batchSize = 10;
    consumerConfig.blockMs = 1000;
    consumerConfig.autoCreateGroup = true;
    consumerConfig.filterByConsumerId = true;

    MessageConsumer consumer(redisPool, consumerConfig, dispatcher);

    // 6. 启动消费者
    consumer.start();

    std::cout << "\n✅ 消费者已启动，监听Stream: " << consumerConfig.streamName << std::endl;
    std::cout << "   Consumer Group: " << consumerConfig.consumerGroup << std::endl;
    std::cout << "   Consumer ID: " << consumerConfig.consumerId << std::endl;
    std::cout << "\n按 Ctrl+C 停止...\n" << std::endl;

    // 7. 主循环（等待停止信号）
    while (g_running) {
        std::this_thread::sleep_for(std::chrono::seconds(1));

        // 定期输出统计信息
        static int counter = 0;
        if (++counter % 10 == 0) {
            auto stats = consumer.getStats();
            std::cout << "📊 统计信息：" << std::endl;
            std::cout << "   接收消息: " << stats.messagesReceived << std::endl;
            std::cout << "   处理成功: " << stats.messagesProcessed << std::endl;
            std::cout << "   处理失败: " << stats.messagesFailed << std::endl;
            std::cout << "   过滤消息: " << stats.messagesFiltered << std::endl;
            std::cout << "   重获消息: " << stats.pendingReclaimed << std::endl;
        }
    }

    // 8. 停止消费者
    std::cout << "\n正在停止消费者..." << std::endl;
    consumer.stop();

    std::cout << "✅ 消费者已停止" << std::endl;

    return 0;
}
